<template>
	<view>
		<view class="header-box">
			<view class="topLogo">
				<image class="logo" src="/static/image/logo.jpg" mode="aspectFit"></image>
			</view>
		</view>
		<!-- input输入框 -->
		<view class="" style="margin-top: -600rpx;">
			<view class="input-group">
				<view class="input-row">
					<image class="img" src="/static/image/login/phone.png" mode="widthFix"></image>
					<input class="input" maxlength="11" type="number" v-model="mobile" placeholder="请输入手机号"
						placeholder-style="color:#ccc;font-size:32rpx;" />
				</view>
				<view class="input-row">
					<image class="img" src="/static/image/login/password.png" mode="widthFix"></image>
					<input class="input" maxlength="11" :type="showPassword ? 'text' : 'password'" v-model="password"
						placeholder-style="color:#ccc !important;font-size:32rpx;" placeholder="请输入密码" />
					<image @click="togglePasswordVisibility" class="img"
						:src="showPassword ? '/static/image/login/eyes-open.png' : '/static/image/login/eyes.png'"
						mode="widthFix"></image>
				</view>
			</view>
			<view class="login-btn">
				<view class="subtn"><button type="primary" @click="loginClick">登录</button></view>
			</view>
			<view class="tips-box flex justify-between">
				<view class="tips" @click="$helper.to('/pages/views/register/register')">
					注册
				</view>
				<view class="tips" @click="$helper.to('/pages/views/forget/forget')">
					忘记密码?
				</view>
			</view>
			
			<view class="login-xie">
				<image @click="clickX"
					:src="isCheckXie == false ? '/static/image/login/choose.png':'/static/image/login/choose_active.png'"
					mode="">
				</image>
				<view class="">
					点击同意<text @click.stop="$helper.to('/pages/views/login/userXy')">《用户协议》</text>和
					<text @click.stop="$helper.to('/pages/views/login/userYs')">《隐私政策》</text>
				</view>
			</view>
		</view>
		<view @click="logout()">登出</view>
	</view>
</template>

<script>
	import tim from '@/common/utils/tim';
	// import { getIMUserSig } from '@/api/im'; // 从后端获取UserSig
	import {
		mapActions,
		mapMutations
	} from "vuex";
	export default {
		data() {
			return {
				mobile: '13938129077',
				password: '123456',
				isCheckXie: false, //协议状态
				showPassword: false, // 新增：控制密码是否可见
				isIMLoggedIn: false // 标记IM是否已登录
			};
		},
		methods: {
			...mapMutations({
				updateUserInfo: 'user/updateUserInfo',
				updateUserToken: 'user/updateUserToken',
				updateIMLoginStatus: 'im/updateLoginStatus',
				updateIMSDKReady: 'im/updateSDKReady'
			}),
			...mapActions({
				loginSuccess: 'user/loginSuccess',
				loginIM: 'im/loginIM'
			}),
			logout(){
				tim.logout()
			},
			// 从后端获取UserSig并登录IM
			async initIM(userID) {
				try {
					// 显示加载提示
					uni.showLoading({
						title: '连接IM中...',
						mask: true
					});
					
					// 获取IM签名
					const res = await this.$http.getIMUserSig({
						user_id: userID
					});
					
					if (res.code === 1) {
						console.log('获取IM签名成功:', res);
						const userSig = res.data.sign;
						uni.setStorageSync('signIM', userSig);
						
						// 确保userID是字符串类型
						const stringUserID = String(userID);
						
						console.log('准备登录IM，用户ID:', stringUserID);
						console.log('UserSig长度:', userSig.length);
						// 登录IM
						try {
							console.log('开始登录IM...');
							const imResponse = await tim.login({
								userID: stringUserID,
								userSig: userSig
							});
							
							console.log('IM登录响应:', imResponse);
							
							// 更新状态
							this.isIMLoggedIn = true;
							this.updateIMLoginStatus(true);
							
							// 设置IM事件监听
							// this.setIMEventListeners();
							
							console.log('IM登录成功，用户ID:', stringUserID);
							return true;
						} catch (imError) {
							console.error('IM登录失败详情:', imError);
							
							// 尝试获取更详细的错误信息
							if (imError.code) {
								console.error('错误代码:', imError.code);
							}
							
							this.$helper.toast('none', `IM登录失败: ${imError.message || '未知错误'}`);
							return false;
						}
					} else {
						this.$helper.toast('none', '获取IM签名失败: ' + res.msg);
						return false;
					}
				} catch (error) {
					console.error('IM登录过程出错:', error);
					this.$helper.toast('none', '登录过程出错，请重试');
					return false;
				} finally {
					uni.hideLoading();
				}
			},
			
			// 设置IM事件监听
			setIMEventListeners() {
				// 监听IM连接状态变化
				tim.on(tim.EVENT.SDK_READY, this.onIMReady);
				tim.on(tim.EVENT.SDK_NOT_READY, this.onIMNotReady);
				tim.on(tim.EVENT.ERROR, this.onIMError);
			},
			
			// IM SDK 已经准备完毕
			onIMReady() {
				console.log('IM SDK已准备完毕，可以发送消息等');
				// 更新SDK准备状态
				this.updateIMSDKReady(true);
			},
			
			// IM SDK 未准备好
			onIMNotReady() {
				console.log('IM SDK未准备好');
				this.isIMLoggedIn = false;
				this.updateIMLoginStatus(false);
				this.updateIMSDKReady(false);
			},
			
			// IM错误处理
			onIMError(event) {
				console.error('IM错误:', event);
			},
			togglePasswordVisibility() {
				this.showPassword = !this.showPassword;
			},
			// 点击协议
			clickX() {
				this.isCheckXie = !this.isCheckXie
			},
			// 登录
			async loginClick() {
				let ph = /^[1][0-9]{10}$/;
				if (!ph.test(this.mobile)) return this.$helper.toast('none', '请输入正确的手机号')
				if (!this.password) return this.$helper.toast('none', '请输入密码')
				if (this.isCheckXie == false) return this.$helper.toast('none', '请同意协议')
				
				try {
					uni.showLoading({
						title: '登录中...'
					});
					
					let params = {
						mobile: this.mobile,
						password: this.password
					}
					
					const res = await this.$http.sendLogin(params);
					
					if (res.code === 1) {
						// 保存用户信息到Vuex
						const userData = res.data;
						this.loginSuccess(userData);
						
						// 登录腾讯IM
						const imLoginSuccess = await this.initIM(userData.id);
						// console.log(111,imLoginSuccess)
						if (imLoginSuccess) {
							this.$helper.toast('success', '登录成功');
							setTimeout(() => {
								this.$helper.to('/pages/views/sex/sex');
							}, 1000);
						}
					} else {
						this.$helper.toast('none', res.msg);
					}
				} catch (error) {
					console.error('登录失败', error);
					this.$helper.toast('none', '登录失败，请重试');
				} finally {
					uni.hideLoading();
				}
			}
		}
	};
</script>

<style lang="scss">
	page {
		background-color: #fff;
	}

	.header-box {
		width: 100%;
		height: 950rpx;

		.topLogo {
			width: 100%;
			text-align: center;
			padding-top: 120rpx;

			.logo {
				width: 180rpx;
				height: 180rpx;
				margin: 0 auto;
				border-radius: 20px;
			}
		}
	}

	/*input输入框*/
	.input-group {
		padding: 32upx 75upx 20upx;

		.input-row {
			line-height: 105upx;
			height: 105upx;
			display: flex;
			position: relative;
			align-items: center;
			border-bottom: 2upx solid #EEEEEE;
			transition: all 0.5s ease-in-out;

			.img {
				width: 32rpx;
				height: 42rpx;
				margin-right: 30upx;
			}

			.input {
				width: 100%;
				font-family: Source Han Sans CN, Source Han Sans CN;
				font-weight: 400;
				font-size: 32rpx;
				color: #000;
				border: none;
			}

			.code-input {
				width: 400upx;
			}

			.code-btn {
				font-size: 24upx;
				display: block;
				line-height: 64upx;
				position: absolute;
				right: 0;
				top: calc(50% - 32upx);
				color: #000000;
				background-color: #fff;
			}
		}


		.invalid-feedback {
			font-size: 24upx;
			color: #c7000a;
			padding-top: 5px;
			padding-left: 20upx;
		}
	}

	/*登录按钮*/
	.login-btn {
		padding: 30upx 50upx;

		.subtn {
			margin-bottom: 30upx;

			button {
				height: 98px;
				background: rgba(51, 51, 51, 0.8);
				width: 100%;
				height: 98rpx;
				text-align: center;
				line-height: 98rpx;
				border-radius: 49rpx;
				font-size: 32rpx;
				font-weight: 500;
				border: none;
				color: #FEC92F;
			}

			button::after {
				border: none;
			}
		}
	}
	.tips-box{
		width: 600rpx;
		margin: 0 auto;
	}
	.tips {
		font-family: Source Han Sans CN, Source Han Sans CN;
		font-weight: 400;
		font-size: 28rpx;
		color: #000;
		line-height: 28rpx;
		text-align: right;
		font-style: normal;
		text-transform: none;
	}

	.login-xie {
		display: flex;
		font-weight: 400;
		font-size: 24rpx;
		color: #ccc;
		width: 480rpx;
		margin: 0 auto;
		bottom: 80rpx;
		position: fixed;
		left: 50%;
		transform: translate(-50%);

		image {
			width: 24rpx;
			height: 24rpx;
			margin: 7rpx 20rpx 0 0;
		}

		text {
			color: #000;
		}
	}
</style>